package showgo.gui;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import showgo.modell.stamm.Person;

public class PersonTableModel extends AbstractTableModel {

    /**
     * 
     */
    private static final long serialVersionUID = 8164010546092013654L;

    private List<Person> personen = new ArrayList<Person>();

    Class<?>[] types = new Class[] { java.lang.String.class,
	    java.lang.String.class, java.lang.String.class,
	    java.lang.Integer.class };

    @Override
    public int getColumnCount() {
	return 4;
    }

    public List<Person> getPersonen() {
	return personen;
    }

    @Override
    public int getRowCount() {
	return personen.size();
    }

    @Override
    public Object getValueAt(int row, int column) {
	switch (column) {
	case 0:
	    return personen.get(row).getName();
	case 1:
	    return personen.get(row).getGebDatum();
	case 2:
	    return personen.get(row).getGeschlecht();
	case 3:
	    return personen.get(row).getWortzahlMerken();
	default:
	    return "";
	}
    }

    public void setValueAt(Object value, int rowIndex, int columnIndex) {
	Person person = personen.get(rowIndex);

	switch (columnIndex) {
	case 0:
	    person.setName((String) value);
	    break;
	case 1:
	    person.setGebDatum((String) value);
	    break;
	case 2:
	    person.setGeschlecht((String) value);
	    break;
	case 3:
	    person.setWortzahlMerken((Integer) value);
	    break;
	}
	fireTableCellUpdated(rowIndex, columnIndex);
    }

    @Override
    public String getColumnName(int column) {
	switch (column) {
	case 0:
	    return "Name";
	case 1:
	    return "Geb.Datum";
	case 2:
	    return "Geschlecht";
	case 3:
	    return "Textmenge";
	default:
	    return "";
	}
    }

    @Override
    public boolean isCellEditable(int row, int column) {
	return false;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
	return types[columnIndex];
    }

    public void addPerson(Person p) {
	personen.add(p);
	fireTableDataChanged();
    }

    public void refresh() {
	fireTableDataChanged();
    }

    public boolean isEmpty() {
	return personen.isEmpty();
    }

    public Person removePersonAt(int rowIndex) {
	Person removedPerson = personen.remove(rowIndex);
	fireTableDataChanged();
	return removedPerson;
    }

    public void removePerson(Person person) {
	personen.remove(person);
	fireTableDataChanged();
    }

    public void replacePerson(Person oldPerson, Person newPerson) {
	personen.set(personen.indexOf(oldPerson), newPerson);
	fireTableDataChanged();
    }

    public Person getPersonAt(int rowIndex) {
	if (rowIndex < personen.size()) {
	    return personen.get(rowIndex);
	}
	return null;
    }
}
